package com.kkb.servlet;

import com.alibaba.fastjson.JSONObject;
import com.kkb.bean.User;
import com.kkb.service.UserService;
import com.kkb.service.impl.UserServiceImpl;
import com.kkb.pojo.ResponseData;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * 登录
 */
@WebServlet("/login")
public class LoginServlet extends HttpServlet {
    private UserService service = new UserServiceImpl();

    @Override
    protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        // 处理参数
        String loginName = req.getParameter("loginName");
        String password = req.getParameter("password");
        // 查询用户
        User user = service.login(loginName, password);
        // 返回信息
        ResponseData respData;
        if (user == null) {
            respData = new ResponseData(false, "用户名或密码错误！！");
        } else {
            respData = new ResponseData("user", user);
            // session 记录 用户信息
            req.getSession().setAttribute("user", user);
        }
        resp.setContentType("text/html;charset=utf-8");
        resp.getWriter().write(JSONObject.toJSONString(respData));
    }
}
